package com.laoye.service.impl;

import com.laoye.Exception.exception.BaseException;
import com.laoye.annotation.Log;
import com.laoye.bean.Order;
import com.laoye.bean.Product_Order;
import com.laoye.dto.OrderCreateDTO;
import com.laoye.dto.OrderDetail;
import com.laoye.dto.OrderEchartsDTO;
import com.laoye.mapper.AddressMapper;
import com.laoye.mapper.OrderMapper;
import com.laoye.mapper.UserMapper;
import com.laoye.service.OrderService;
import com.laoye.util.EmailUtil;
import com.laoye.util.ThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @CacheEvict(value = "orderList", allEntries = true)
    @Override
    @Transactional
    @Log("订单创建")
    public void addOrder(OrderCreateDTO orderdto) {
        if (orderdto.getProducts() == null || orderdto.getProducts().isEmpty()){
            throw new BaseException(401,"请选择商品");
        }
        Order order = new Order();
        order.setCreate_time(LocalDateTime.now());
        order.setUser_id(ThreadLocal.getCurrentId());
        order.setOrder_no(UUID.randomUUID().toString());
        // 补充前端传递的订单信息（如addr_id、pay_type等，需从orderdto中获取）
        order.setAddr_id(orderdto.getOrder().getAddr_id()); // 假设前端传递了addr_id
        order.setPay_type(orderdto.getOrder().getPay_type());
        order.setTotal_amount(orderdto.getOrder().getTotal_amount());
        order.setStatus((byte) 0); // 待支付状态
        orderdto.setOrder(order);
        orderMapper.addOrder(orderdto);
        orderMapper.addOrderProducts(orderdto);
    }

    @Override
    public Order getOrderById(Integer order_id) {
        if (order_id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        return orderMapper.getOrderById(order_id);
    }

    @Cacheable(value = "orderList",
            key = "'List_order_' + #order_id + '_user_' + T(com.laoye.util.ThreadLocal).getCurrentId()")
    @Override
    public List<Product_Order> getProductById(Integer order_id) {
        if (order_id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        return orderMapper.getProductById(order_id);   //根据id获取订单商品列表
    }

    @CacheEvict(value = "orderList", allEntries = true)
    @Override
    @Log("订单支付")
    public void updateSetPayTime(Integer id) {
        if (id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        orderMapper.updateSetPayTime(id);
    }

    @Cacheable(value = "orderList", key = "'orderList_status_' + #status")
    @Override
    public List<OrderDetail> getOrderList(Byte status) {
        if (status == null){
            throw new BaseException(401,"订单状态不能为空");
        }
        return orderMapper.getOrderList(status); //管理员根据订单状态获取订单列表
    }


    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional
    @CacheEvict(value = "orderList", allEntries = true)
    @Log("订单发货")
    public void updateDeliveryTime(Integer id) {  //管理员发货
        if (id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        orderMapper.updateDeliveryTime(id);
        Integer userId = orderMapper.getUserId(id);  //获取用户id
        String email = userMapper.getEmail(userId);  //获取用户邮箱
        //像邮箱发送邮件
        if (email != null) {
            EmailUtil.sendEmail(email, "订单已发货，请及时查看！");
        }
        System.out.println("---------------------------------发送邮件成功-----------------------------");
    }

    @Transactional
    @CacheEvict(value = "orderList", allEntries = true) //删除订单时删除所有与order有关的缓存
    @Override
    @Log("订单删除")
    public void deleteOrder(Integer id) {
        if (id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        orderMapper.deleteOrder(id);
        orderMapper.deleteOrderProducts(id);
    }

    @Cacheable(value = "orderList",
            key = "'OrderDetail_user_' + T(com.laoye.util.ThreadLocal).getCurrentId() + '_status_' + #status")
    @Override
    public List<OrderDetail> getUserOrderList(Byte status) {
        if (status == null){
            throw new BaseException(401,"订单状态不能为空");
        }
        return orderMapper.getUserOrderList(status, ThreadLocal.getCurrentId()); //用户根据订单状态获取订单列表
    }

    /**
     * 订单完成，修改订单状态为已完成
     *
     * @param id 订单id
     */
    @CacheEvict(value = "orderList", allEntries = true)
    @Override
    @Log("用户确认收货，订单完成")
    public void completeOrder(Integer id) {
        if (id == null){
            throw new BaseException(401,"订单id不能为空");
        }
        orderMapper.completeOrder(id);
    }


    /**
     * 获取订单数量
     *
     * @return 返回数据给echarts表
     */
    @Override
    public List<OrderEchartsDTO> getOrderCount() {
        Integer count1 = orderMapper.getOrderCount1();
        Integer count2 = orderMapper.getOrderCount2();
        Integer count3 = orderMapper.getOrderCount3();
        Integer count4 = orderMapper.getOrderCount4();
        List<OrderEchartsDTO> list = new ArrayList<>();
        list.add(new OrderEchartsDTO(count1, "待支付"));
        list.add(new OrderEchartsDTO(count2, "待发货"));
        list.add(new OrderEchartsDTO(count3, "待收货"));
        list.add(new OrderEchartsDTO(count4, "已完成"));
        return list;
    }
}
